package com.taichuan.selfcheck.ui.activity;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.taichuan.keysupport.Key;
import com.taichuan.mvp.fragment.BaseFragment;
import com.taichuan.selfcheck.R;
import com.taichuan.selfcheck.db.DaoManager;
import com.taichuan.selfcheck.entity.TestResultEntity;
import com.taichuan.selfcheck.entity.greendao.dao.TestResultEntityDao;
import com.taichuan.selfcheck.mvp.presenter.MainPresenter;
import com.taichuan.selfcheck.mvp.viewinterface.MainInterface;
import com.taichuan.selfcheck.persistent.PersistentManager;
import com.taichuan.selfcheck.service.SelfcheckSerialPortService;
import com.taichuan.selfcheck.ui.activity.base.KeySupportBaseActivity;
import com.taichuan.selfcheck.ui.fragment.CardFragment;
import com.taichuan.selfcheck.ui.fragment.IOStateFragment;
import com.taichuan.selfcheck.ui.fragment.LightTestFragment;
import com.taichuan.selfcheck.ui.fragment.MainFragment;
import com.taichuan.selfcheck.ui.fragment.MainFragment2;
import com.taichuan.selfcheck.ui.fragment.MainFragment3;
import com.taichuan.selfcheck.ui.fragment.ScreenTouchFragment;
import com.taichuan.selfcheck.ui.fragment.SelectScreenTestFragment;
import com.taichuan.selfcheck.ui.fragment.TestAudioFragment;
import com.taichuan.selfcheck.ui.fragment.TestCameraFragment;
import com.taichuan.selfcheck.ui.fragment.VideoTestFragment;
import com.taichuan.selfcheck.ui.fragment.WiFiFragment;
import com.taichuan.selfcheck.ui.fragment.base.AppBaseFragment;
import com.taichuan.tcutils.common.SystemInfoUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;

/**
 * 该类主要用于
 *
 * @author CamelLuo
 * @version 2019/12/4
 */
public class MainActivity extends KeySupportBaseActivity<MainInterface, MainPresenter> implements MainInterface {

    /**
     * 定义一个ResultCode用于返回结果给打开该App的应用
     */
    public static final int FINISH_SELF_CHECK_APP_RESULT_CODE = 101;
    /**
     * 定义一个key用于传递给 功能测试自检程序 App 跳转后 初始化串口库时 是否需要关闭看门狗
     */
    public static final String TC_SELF_CHECK_PARAM_IS_CLOSE_FEED_DOG = "TC_SELF_CHECK_PARAM_IS_CLOSE_FEED_DOG";
    /**
     * 定义一个key用于供外部程序跳转 功能测试自检程序 App 时附带的 门口机程序连接平台的url地址
     */
    public static final String TC_SELF_CHECK_PARAM_CLOUD_PLATFORM_URL = "TC_SELF_CHECK_PARAM_CLOUD_PLATFORM_URL";
    /**
     * 定义一个key用于供外部程序跳转 功能测试自检程序 App 时附带的 门口机程序所连接硬件云SDK的tcp地址
     */
    public static final String TC_SELF_CHECK_PARAM_IOT_SDK_TCP_URL = "TC_SELF_CHECK_PARAM_IOT_SDK_TCP_URL";
    /**
     * 定义一个key用于供外部程序跳转 功能测试自检程序 App 时附带的 第三方跳转App的包名，用于判断是由哪个App跳转过来
     */
    public static final String TC_SELF_CHECK_PARAM_THREE_APP_PACKAGE_NAME = "TC_SELF_CHECK_PARAM_THREE_APP_PACKAGE_NAME";

    //当前是否处于自动测试
    public boolean isAutoTest = false;
    //用于更改媒体音量
    AudioManager audioManager;

    @BindView(R.id.activity_main_version_info_textView)
    TextView versionInfoTv;
    @BindView(R.id.selfCheckTitle)
    TextView selfCheckTitle;

    /**
     * 定义一个变量用于表示是否需要通知 SelfcheckSerialPortService 关闭看门狗
     */
    private boolean isCloseFeedDog = true;
    /**
     * 定义一个变量用于表示本次程序启动是否由 第三方App发起
     */
    private boolean isStartAppByThree = false;
    private Intent intent;

    /**
     * 用于测试结果数据存储
     */
    public static List<String[]> testResultList = new ArrayList<>();

    private List<TestResultEntity> resultList=new ArrayList<>();
    private String threeAppPackageName;


    @Override
    public void onInputKeyEvent(int inputKeyCode) {

    }

    @Override
    protected boolean isAllowAutoFinishActivity() {
        return false;
    }

    @Override
    protected void doOnAutoFinishActivity() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
    }

    @Override
    protected int setContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView(Bundle bundle) {
        //获取版本信息
        String versionInfo = SystemInfoUtils.getSoftwareVersion(this).replace("\n", "-") +
                " | VersionCode: " + SystemInfoUtils.getSoftwareVersionCode(this);
        versionInfoTv.setText(versionInfo);

        selfCheckTitle.setText(getStrById(R.string.settings_function_test));

        //初始化Fragment管理器
        initBaseFragmentManager(getSupportFragmentManager(), R.id.selfcheck_container, null);
        //添加MainFragment
        mBaseFragmentManager.add(new MainFragment());

        //解析传入的Intent信息
        parseUriScheme();

        //初始化串口库
        intent = new Intent(this, SelfcheckSerialPortService.class);
        //附带参数信息，是否需要关闭看门狗
        intent.putExtra(TC_SELF_CHECK_PARAM_IS_CLOSE_FEED_DOG, isCloseFeedDog);
        startService(intent);

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销EventBus
        EventBus.getDefault().unregister(this);
        //注销Service
        stopService(intent);
        //将进程结束
        Process.killProcess(Process.myPid());
    }

    private void parseUriScheme() {
        if (getIntent() != null) {
            //获取Uri数据
            Uri uri = getIntent().getData();
            if (uri != null) {
                //本次启动App由外部组件开启，并传入了 Scheme Uri协议链接
                if (uri.compareTo(Uri.parse("tcselfcheck://com.taichuan.selfcheck/open")) == 0) {
                    Log.i(TAG, "parseUriScheme: 接收到 外部组件打开 功能测试自检程序 Scheme Uri 请求");
                    //获取参数信息
                    isCloseFeedDog = getIntent().getBooleanExtra(TC_SELF_CHECK_PARAM_IS_CLOSE_FEED_DOG, true);
                    String cloudPlatformUrl = getIntent().getStringExtra(TC_SELF_CHECK_PARAM_CLOUD_PLATFORM_URL);
                    String iotSdkTcpUrl = getIntent().getStringExtra(TC_SELF_CHECK_PARAM_IOT_SDK_TCP_URL);
                    threeAppPackageName = getIntent().getStringExtra(TC_SELF_CHECK_PARAM_THREE_APP_PACKAGE_NAME);
                    Log.e(TAG, "获取到门口机App传递的参数信息 | 是否关闭看门狗： " + isCloseFeedDog +
                            "  门口机所登录平台地址： " + cloudPlatformUrl + "  硬件云SDKmqttTcp地址： " + iotSdkTcpUrl + "" +
                            " | 打开的第三方App的包名为： " + threeAppPackageName);
                    PersistentManager.get().setCloudPlatformUrl(cloudPlatformUrl);
                    PersistentManager.get().setIotSdkTcpUrl(iotSdkTcpUrl);

                    //TODO 由外部组件打开时需要执行的操作
                    setStartAppByThree(true);
                }
            }
        }
    }

    @Override
    public void onXmlClick(View v) {
        super.onXmlClick(v);
        switch (v.getId()) {
            case R.id.setting_backFl: {
                String title = selfCheckTitle.getText().toString();
                //根据 . 来分割字符串需要进行转义
                String[] functionNum = title.split("\\.");
                Log.i(TAG, "onXmlClick: 标题的内容为：" + title + ",分割后的内容为：" + functionNum[0]);
                if (getString(R.string.settings_function_test).equals(title)) {
                    //结束程序
                    finishApp();
                } else {
                    ((AppBaseFragment) mBaseFragmentManager.getCurrentFragment()).doOnAutoFinishFragment();
                }

                break;
            }
        }
    }

    private void finishApp() {
//        if (SystemUtils.getTcDeviceType() == TcDeviceType.L10_Pro) {
//            /**
//             * 因为L10Pro不知道是什么原因导致调用finish后，
//             * 系统无法finish掉activity，导致10s超时，
//             * 出现当前App UI黑屏无法退出现象，但是代码正常运行，
//             * 所以改为直接结束进程
//             */
//            //注销EventBus
//            EventBus.getDefault().unregister(this);
//            //注销Service
//            stopService(intent);
//            //将进程结束
//            Process.killProcess(Process.myPid());
//        } else {
            //结束程序，并返回结果码给跳转应用
            Intent intent = new Intent();
            finish(FINISH_SELF_CHECK_APP_RESULT_CODE, intent);
//        }
    }

    @Override
    public void getIntentExtras(Intent intent) {

    }

    @Override
    protected boolean isNeedToolbar() {
        return false;
    }

    @Override
    protected boolean isNeedStatusBarFontDark() {
        return false;
    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter();
    }

    /**
     * 显示标题
     *
     * @param titleId 标题
     */
    public void showToolBarTitle(int titleId) {
        if (selfCheckTitle != null) {
            selfCheckTitle.setText(titleId);
        }
    }


    public boolean isStartAppByThree() {
        return isStartAppByThree;
    }

    public void setStartAppByThree(boolean startAppByThree) {
        isStartAppByThree = startAppByThree;
    }

    public String getThreeAppPackageName() {
        return threeAppPackageName;
    }

    public boolean checkIsTcDoorApp(){
        if (!TextUtils.isEmpty(getThreeAppPackageName())){
            if (getThreeAppPackageName().equals("com.taichuan.u9.dh") ||
                    getThreeAppPackageName().equals("com.taichuan.cocu9h")){     //太川门禁App包名
                return true;
            }else {
                return false;
            }
        }else {         //不传入包名的也判定为false
            return false;
        }
    }

    /**
     * 分发按键事件 以及 可取消自动测试
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        Log.d(getClass().getSimpleName(), "dispatchKeyEvent keyCode : "
                + event.getKeyCode());
        //重新计时操作
        resumeAutoFinishTimer();
        //长按 # 号键取消自动测试
//        if (isAutoTest){
//            if (event.getKeyCode() == KeyEvent.KEYCODE_MEDIA_RECORD){
//                isAutoTest = false;
//            }
//        }


        if (mBaseFragmentManager.getCurrentFragment() != null) {
            BaseFragment currentFragment = mBaseFragmentManager.getCurrentFragment();
            if (currentFragment instanceof MainFragment ||
                    currentFragment instanceof MainFragment2||
                    currentFragment instanceof MainFragment3) { //主页Fragment：  MainFragment，MainFragment2

                if (event.getKeyCode() == Key.Convert.KEYCODE_XING) {           //主页Fragment下按下*号键
                    findViewById(R.id.setting_backFl).performClick();
                    return true;
                } else if (event.getKeyCode() == Key.Convert.KEYCODE_0) {         //切换测试页面，按下 0号键切换
                    mPresenter.switchFunctionPageByKeyEvent(event, mBaseFragmentManager);
                } else {                                                         //其他按键，交由主页Fragment处理逻辑交互
                    boolean result = currentFragment.dispatchKeyEvent(event);
                    Log.e(TAG, "dispatchKeyEvent: 主页Fragment: " + currentFragment.getClass().getSimpleName() + " 按键事件执行结果：  " + result);
                    return result ? result : super.dispatchKeyEvent(event);
                }
                return super.dispatchKeyEvent(event);

            } else {                                                         //除主页外的功能测试Fragment的按键事件交互逻辑交由Fragment处理
                boolean result = currentFragment.dispatchKeyEvent(event);
                Log.e(TAG, "dispatchKeyEvent: 功能测试Fragment: " + currentFragment.getClass().getSimpleName() + " 按键事件执行结果：  " + result);
                return result ? result : super.dispatchKeyEvent(event);
            }
        } else {
            Log.e(TAG, "dispatchKeyEvent: 点击按键时无法获取到当前FragmentManager实例对象，请稍后再试");
            return super.dispatchKeyEvent(event);
        }
    }

    /**
     * 定义一个方法用于让按键版设备点击返回键时需要执行的流程
     */
    public void clickBackKey(){
        findViewById(R.id.setting_backFl).performClick();
    }

    /**
     * 在视频测试页面时进行处理，上下滑动屏幕调整音量
     * 在主页面时，左右滑动，切换测试页面
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        if (mBaseFragmentManager.getCurrentFragment() instanceof VideoTestFragment) {
            mPresenter.changeVolumeByTouch(event, audioManager);
        } else if (selfCheckTitle.getText().toString().equals(getString(R.string.settings_function_test))) {
            mPresenter.switchFunctionPageByTouch(event, mBaseFragmentManager);
        }
        return super.dispatchTouchEvent(event);
    }


    /**
     * 功能如下：
     * 1、自动测试
     * 2、通过EventBus接收测试结果，并存储
     *
     * @param testResult
     */
    @Subscribe
    public void onResultEvent(TestResultEntity testResult) {
        if (!testResult.getTestContent().equals(getResources().getString(R.string.auto_check))) {       //非自动测试，收到普通功能测试结果发布事件
            Log.i(TAG, "onResultEvent: 测试内容：" + testResult.getTestContent() + " 测试结果：" + testResult.getTestResult());
            TestResultEntityDao resultEntityDao= DaoManager.getInstance().getDaoSession().getTestResultEntityDao();
            resultEntityDao.insertOrReplace(testResult);
            if (isAutoTest) {                //自动测试时的逻辑
                switch ((int)testResult.getOrderBy()) {
                    case 1:       //如果当前结束的为第1个模块，屏幕颜色测试模块，则存储完结果启动下一个测试模块
                        if (isTouchDevice) {
                            mBaseFragmentManager.replace_remove_add(new ScreenTouchFragment());     //如果为触屏型设备，则进行触屏测试
                            selfCheckTitle.setText(getStrById(R.string.screentouch));
                        } else {
                            mBaseFragmentManager.replace_remove_add(new TestAudioFragment());      //如果为按键型设备，则跳过触屏测试
                            selfCheckTitle.setText(getStrById(R.string.microphone));
                        }
                        break;
                    case 2:       //如果当前结束的为第2个模块，屏幕触摸测试模块，则存储完结果启动下一个测试模块，下同
                        mBaseFragmentManager.replace_remove_add(new TestAudioFragment());
                        selfCheckTitle.setText(getStrById(R.string.microphone));
                        break;
                    case 3:
                        mBaseFragmentManager.replace_remove_add(new TestCameraFragment());
                        selfCheckTitle.setText(getStrById(R.string.camera));
                        break;
                    case 4:
                        mBaseFragmentManager.replace_remove_add(new IOStateFragment());
                        selfCheckTitle.setText(getStrById(R.string.device_test));
                        break;
                    case 5:
                        mBaseFragmentManager.replace_remove_add(new WiFiFragment());
                        selfCheckTitle.setText(getStrById(R.string.wifi));
                        break;
                    case 6:
                        mBaseFragmentManager.replace_remove_add(new CardFragment());
                        selfCheckTitle.setText(getStrById(R.string.swipecard));
                        break;
                    case 7:
                        mBaseFragmentManager.replace_remove_add(new LightTestFragment());
                        selfCheckTitle.setText(getStrById(R.string.light_test));
                        break;
                    case 8:
                        mBaseFragmentManager.replace_remove_add(new VideoTestFragment());
                        selfCheckTitle.setText(getStrById(R.string.video_test));
                        break;
                    case 13:                      //到最后一个功能时，复位自动测试标志位，并返回主页面
                        isAutoTest = false;
                        selfCheckTitle.setText(getStrById(R.string.settings_function_test));
                        mBaseFragmentManager.superBack();
                        break;
                }
            } else {                 //非自动测试，手动点进指定功能测试模块时的逻辑
                mBaseFragmentManager.superBack();
                selfCheckTitle.setText(getStrById(R.string.settings_function_test));
            }
        } else if (testResult.getTestContent().equals(getResources().getString(R.string.auto_check))) {                     //收到自动测试事件
            if (!isAutoTest) {
                isAutoTest = true;
                mBaseFragmentManager.replace(new SelectScreenTestFragment());
                selfCheckTitle.setText(getStrById(R.string.screencolor));
            }
        } else {
            mBaseFragmentManager.superBack();
        }
    }
}
